package com.gexiaobao.pigeon.ui.fragment.mine.tools.line

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.setFragmentResultListener
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.services.help.Tip
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.FragmentMapSelectPointBinding
import com.gexiaobao.pigeon.viewmodel.MatchLineQueryViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat

/**
 * @Author      : hxw
 * @Date        : 2023/6/1 9:33
 * @Describe    : 定位取点
 */
class FragmentMapSelectPoint : BaseFragment<MatchLineQueryViewModel, FragmentMapSelectPointBinding>(),
    AMap.OnCameraChangeListener,
    AMap.OnMapLoadedListener {

    private var isStart: Boolean = true
    private var mapView: MapView? = null
    private var aMap: AMap? = null
    private var relon = ""
    private var relat = ""

    //声明mLocationClient对象
    lateinit var mLocationClient: AMapLocationClient

    //声明mLocationOption对象
    lateinit var mLocationOption: AMapLocationClientOption

    override fun initView(savedInstanceState: Bundle?) {
        //隐私合规检查
        AMapLocationClient.updatePrivacyShow(context, true, true)
        AMapLocationClient.updatePrivacyAgree(context, true)
        mapView = activity?.findViewById<View>(R.id.map_catch_point) as MapView
        mapView!!.onCreate(savedInstanceState) // 此方法必须重写
        mDatabind.toolbar.initClose("定位取点") {
            nav().navigateUp()
        }

        //设置是否只定位一次,默认为false
        mLocationClient = AMapLocationClient(context)
        //初始化定位参数
        mLocationOption = AMapLocationClientOption()
        //设置定位监听
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.interval = 2000
        //设置定位参数
        mLocationOption.isOnceLocation = true
        mLocationClient.setLocationOption(mLocationOption)

        init()
        aMap!!.setOnCameraChangeListener(this)
        aMap!!.setOnMapLoadedListener(this)

        setFragmentResultListener("RESULT_CODE_INPUT_TIPS") { _, bundle ->
            val tip: Tip? = bundle.getParcelable(Constant.EXTRA_TIP)
            if (tip != null) {
                if (tip.point == null) {
                    RxToast.showToast("获取关键字点位失败")
                    return@setFragmentResultListener
                }
            }

            mDatabind.mainKeywords.text = tip!!.name
            mDatabind.mapCatchPoint.map.moveCamera(
                CameraUpdateFactory.newLatLngZoom(
                    LatLng(
                        tip.point.latitude,
                        tip.point.longitude
                    ), 12f
                )
            )
            if (tip.name != "") {
                mDatabind.mainKeywords.visibility = View.VISIBLE
            }
        }
    }

    private fun init() {
        if (aMap == null) {
            aMap = mapView!!.map
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvFinish, mDatabind.mainKeywords, mDatabind.cleanKeywords) {
            when (it) {
                mDatabind.tvFinish -> {
                    setFragmentResult("requestMap", Bundle().apply {
                        putString("relon", relon)
                        putString("relat", relat)
                        if (isStart) {
                            putBoolean("type", true)
                        } else {
                            putBoolean("type", false)
                        }
                    })
                    nav().navigateUp()
                }

                mDatabind.mainKeywords -> {
                    nav().navigateAction(R.id.action_to_input_tip)
                }

                mDatabind.cleanKeywords -> {
                    mDatabind.mainKeywords.text = ""
                    mDatabind.mainKeywords.visibility = View.GONE
                }
            }
        }
    }

    /**
     * 方法必须重写
     */
    override fun onResume() {
        super.onResume()
        mapView!!.onResume()
    }

    /**
     * 方法必须重写
     */
    override fun onPause() {
        super.onPause()
        if (mapView != null) {
            mapView!!.onPause()
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mapView!!.onSaveInstanceState(outState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mapView != null) {
            mapView!!.onDestroy()
        }
    }

    override fun onCameraChange(position: CameraPosition?) {
        val target = position?.target
        if (target != null) {
            relat = target.latitude.toString()
            relon = target.longitude.toString()
        }
    }

    override fun onCameraChangeFinish(p0: CameraPosition?) {
    }

    override fun onMapLoaded() {
        addMarkerInScreenCenter()
    }

    private var locationMarker: Marker? = null

    @SuppressLint("InflateParams")
    private fun addMarkerInScreenCenter() {
        val latLng = aMap!!.cameraPosition.target
        val screenPosition = aMap!!.projection.toScreenLocation(latLng)
        val markerOption2 = MarkerOptions()
        val view = layoutInflater.inflate(R.layout.distance_location_popup, null)
        markerOption2.icon(BitmapDescriptorFactory.fromView(view))
        locationMarker = aMap!!.addMarker(markerOption2)
        //设置Marker在屏幕上,不跟随地图移动
        locationMarker!!.setPositionByPixels(screenPosition.x, screenPosition.y)
        locationMarker!!.showInfoWindow()

        try {
            val islocation = arguments?.getBoolean("islocation", true)
            isStart = requireArguments().getBoolean("is_start", false)
            val lon = arguments?.getDouble("lon")
            val lat = arguments?.getDouble("lat")
            if (islocation == true) {
                mLocationClient.setLocationListener {
                    mDatabind.mapCatchPoint.map.moveCamera(
                        CameraUpdateFactory.newLatLngZoom(
                            LatLng(
                                it.latitude,
                                it.longitude
                            ), 6f
                        )
                    )
                }
                mLocationClient.startLocation()
            } else {
                mDatabind.mapCatchPoint.map.moveCamera(CameraUpdateFactory.newLatLngZoom(lat?.let {
                    lon?.let { it1 ->
                        LatLng(
                            it,
                            it1
                        )
                    }
                }, 6f))
            }
        } catch (e: Exception) {
            RxToast.showToast("点位前置信息错误")
            nav().navigateUp()
        }
    }
}